/**
 * Created by tanbingqin on 2019/10/29.
 */
import React  from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { messages, dealCache, queryCurrencyPrecision } from 'share/common'
import { Form, Table, Button, Tag, Input, Popover, Dropdown, Icon, Menu, message, Modal, Select, InputNumber, Checkbox } from 'antd'
import moment from 'moment'
import AdvancedTable from 'components/advanced-table'
import expenseRecordService from 'containers/expense-record/expense-record.service'
import RefundModal from 'containers/expense-record/refund-modal'
import errorMessage from 'share/errorMessage'

class ExpenseRecordList extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      currentPageAmount: 0, //当前页的金额合计
      processLoading: false, //当前table有操作的loading
      searchForm: [
        {
          component: 'Selector',
          id: 'setOfBooksId',
          label: messages('request-5.key1')/*账套*/,
          props: {
            type: 'setOfBooksByTenant',
            params: {roleType: 'TENANT'}
          },
          parser: value => ({
            setBookOfIds: value ? [value] : null
          })
        },
        {
          component: 'Chooser',
          id: 'companyOIDs',
          label: messages('request-5.key2')/*公司*/,
          props: {
            labelKey: 'name',
            valueKey: 'companyOID',
            type: 'enabled_company' //'permission_company',
          },
          parser: value => ({
            companyOIDs: value ? value.map(item => item.companyOID) : null
          })
        },
        {
          id: 'userOIDs', label: messages('request-5.key3')/*员工*/,
          component: 'Chooser',
          props: {
            type: 'user_condition',
            labelKey: 'fullName',
            valueKey: 'userOID',
            listExtraParams: {
              roleType: 'TENANT'
            },
            dataIndex: 'applicantName'
          },
          parser: value => ({
            userOIDs: value ? value.map(item => item.userOID) : null
          }),
          JSONObjectFormatterParams: ['fullName', 'userOID']
        },
        {
          id: 'submittedDate', label: messages('common.date')/*日期*/,
          component: 'DateRangePicker',
          parser: value => ({
            startDateTime: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
            endDateTime: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
          }),
          dataIndex: 'submittedDate'
        },
        {
          id: 'tnxNo', label: messages('request-5.key4')/*交易号*/, component: 'Input',
          props: {
            placeholder: messages('common.please.input')/*请输入*/
          }
        },
        {
          id: 'orderTypes', label: messages('request-5.key5')/*记录类型*/,
          component: <Checkbox.Group>
            <Checkbox value="SPEND">{messages('request-5.key6')/*消费*/}</Checkbox>
            <Checkbox value="REFUND">{messages('request-5.key7')/*退货*/}</Checkbox>
          </Checkbox.Group>,
          initialValue: ["SPEND", "REFUND"],
          tagParser: value => {
            let nameList = [];
            value.length && value.map(item => {
              nameList.push(item === "SPEND" ? messages('request-5.key6')/*消费*/ : messages('request-5.key7')/*退货*/);
            });
            return nameList.join(',');
          }
        },
        {
          id: 'supplierCode', label: messages('request-5.key8')/*卡服务商*/, component: 'Selector',
          props: {
            type: 'cardSupplier',
            params: {
              enabled: true,
              type: 5033,
              roleType: 'TENANT'
            }
          }
        },
        {
          id: 'amount', label: messages('common.amount')/*金额*/,
          component: <InputNumber
            style={{width: '100%'}}
            precision={2}
            min={0}
            step={1}
            placeholder={messages('common.please.input')/*请输入*/}
          />,
          tagParser: value => this.filterMoney(value, 2)
        },
      ],
      columns: [
        {
          title: messages('request-5.key1')/*账套*/, dataIndex: 'setOfBooksName', width: '10%',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-5.key2')/*公司*/, dataIndex: 'companyName', width: '10%',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-5.key8')/*卡服务商*/, dataIndex: 'supplierName', width: '10%',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-5.key9')/*员工姓名*/, dataIndex: 'userName', width: '10%',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-5.key10')/*消费卡号*/, dataIndex: 'cardNumber', width: '10%',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-5.key4')/*交易号*/, dataIndex: 'tnxNo', width: '10%',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-5.key11')/*交易时间*/, dataIndex: 'orderCreateTime', width: 200,
          render: (value, record) => moment(value).format('YYYY-MM-DD HH:mm:ss')
        },
        {
          title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 60
        },
        {
          title: messages('request-5.key12')/*商户*/, dataIndex: 'merName', width: '10%',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('common.amount')/*金额*/, dataIndex: 'amount', width: '10%',
          render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
        },
        {
          title: messages('request-5.key13')/*交易类型*/, dataIndex: 'orderTypeName', width: '10%'
        },
        {
          title: messages('request-5.key14')/*原交易号*/, dataIndex: 'originalOrderId', width: '10%',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-5.key15')/*生成借/还款单号*/, dataIndex: 'referenceBusinessCodes', width: '15%',
          render: (value, record) => {
            if (record.orderType === 'REFUND') {
              let businessCodeList = [];
              record.refRepaymentList && record.refRepaymentList.map(item => {
                businessCodeList.push(item.businessCode);
              });
              return (
                <div>
                  {!!businessCodeList.length && (
                    <span style={{whiteSpace: 'normal'}}>{businessCodeList.join(',')}&nbsp;&nbsp;&nbsp;</span>
                  )}
                </div>
              )
            } else {
              return (
                <div>{record.refBusinessCode}</div>
              )
            }
          }
        },
        {
          title: messages('request-5.key16')/*错误信息*/, dataIndex: 'msg', width: '15%',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-5.key17')/*可生成余额*/, dataIndex: 'wirteOffAmount', width: '15%',
          render: (value, record) => {
            let isHas = Math.abs(value) > 0; //是否还有余额
            if (record.orderType === 'REFUND') {
              return (
                <span>
                  {this.filterMoney(value, queryCurrencyPrecision(record.currencyCode), true)}&nbsp;&nbsp;&nbsp;
                  {isHas && (
                    <span style={{cursor: 'pointer', color: '#0092da'}} onClick={() => this.handleRetryRefund(record)}>
                      <Icon type="reload" />&nbsp;{messages('request-5.key18')/*继续生成*/}
                    </span>
                  )}
                </span>
              )
            } else {
              return record.refBusinessCode ? this.filterMoney(value, queryCurrencyPrecision(record.currencyCode), true) : (
                <span style={{cursor: 'pointer', color: '#0092da'}} onClick={() => this.handleRetryLoan(record)}>
                  <Icon type="reload" />&nbsp;{messages('request-5.key18')/*继续生成*/}
                </span>
              );
            }
          }
        }
      ],
      visible: false, //还款弹框是否展示
      modalRecordData: null //还款弹框展示的那一行的表格数据
    }
  }

  componentWillMount(){}

  componentDidMount(){

  }

  service = (page, pageSize, searchParams) => {
    return expenseRecordService.getExpenseRecordList(page, pageSize, searchParams);
  };

  onGetData = (dataSource, pagination, searchParams) => {
    let currentPageAmount = 0;
    dataSource.length && dataSource.map(record => {
      currentPageAmount += record.amount;
    });
    this.setState({currentPageAmount});
  };

  handleModalShow = (record) => {
    this.setState({
      modalRecordData: JSON.parse(JSON.stringify(record)),
      visible: true
    });
  };

  handleModalCancel = () => {
    this.setState({visible: false});
  };

  handleModalOk = () => {
    this.setState({visible: false});
    this.advancedTableRef.getList(true);
  };

  //额度创建借款单失败时，手动进行重新创建
  handleRetryLoan = (record) => {
    this.setState({processLoading: true});
    expenseRecordService.retryCreateLoan(record.id).then(res => {
      if (res.data.status === 1004) {
        message.error(res.data.msg);
      } else {
        message.success(messages('request-5.key19')/*创建成功*/);
      }
      this.advancedTableRef.getList(true);
    }).catch(err => {
      errorMessage(err.response);
    }).finally(() => {
      this.setState({processLoading: false});
    });
  };

  //还款单继续生成
  handleRetryRefund = (record) => {
    this.setState({processLoading: true});
    expenseRecordService.retryCreateRefund(record.id).then(res => {
      if (res.data.status === 1006) {
        message.error(messages('request-5.key20')/*生成失败：*/ + res.data.msg);
      } else if (res.data.status === 1005) {
        message.success(messages('request-5.key21')/*生成单据成功*/);
      }
      this.advancedTableRef.getList(true);
    }).catch(err => {
      errorMessage(err.response);
    }).finally(() => {
      this.setState({processLoading: false});
    });
  };

  render(){
    const { columns, searchForm, currentPageAmount, visible, modalRecordData, processLoading } = this.state;
    return(
      <div className="full-height-page">
        <AdvancedTable
          index
          loading={processLoading}
          title={messages('request-5.key22')/*消费记录*/}
          columns={columns}
          searchForm={searchForm}
          service={this.service}
          rowKey="tnxNo"
          tableName='expense-record-list'
          onGetData={this.onGetData}
          expandAll
          onRef={ref => this.advancedTableRef = ref}
          footer={
            <span>
              {messages('request-5.key23')/*合计*/}：
              {this.filterMoney(currentPageAmount, 2)}
            </span>
          }
        />
        <RefundModal
          visible={visible}
          onCancel={this.handleModalCancel}
          onOk={this.handleModalOk}
          recordData={modalRecordData}
        />
      </div>
    )
  }
}

ExpenseRecordList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language
  }
}

export default connect(mapStateToProps)(ExpenseRecordList)


